define(["jquery", "bbcare",
    "scprit/department/vm/assessmentScreening/bsid3.ui.js",
    "scprit/department/vm/assessmentScreening/assessmentScreeningQuestion.servers.js"], function ($,$bb,$ui,$servers) {
    var event = {};
    event.tabClick = function(data,scoreObj){
        var _this = this;
        $("#testSelect").off('click','div.item-label');
        $("#testSelect").on('click','div.item-label',function(){
            isChecked(scoreObj);
            var quesType = $(this).attr("quesType");
            $(this).addClass("selected").siblings().removeClass("selected");
            if(quesType == "behavior"){
                var dataQues = data[quesType];
                $("#stage-tabs").html("");
                $("#node").html("");
                $ui.behaviorInit({"id":"#main","data":dataQues});
                _this.behaviorFn(data,quesType,scoreObj);
            }else{
                var diff = $(this).attr("devAge")*1;
                $("#intellgenceAge").html(getMonthAge(diff));
                var start = $("#"+quesType).parent("div").attr("start");//起始阶段名
                var end = $("#"+quesType).parent("div").attr("end");//结束阶段名；
                var isEnding = $(this).attr("isEnding");
                $ui.nodeInit({"id":"#node","data":{"start":start,"end":end}});
                _this.quesInit(data,quesType,diff,'',scoreObj,start,end);
            }
        });
    };
    //转换为 xx月xx天：
    var getMonthAge = function(days){
        var monthAge = parseInt(days/30) > 0 ? parseInt(days/30) + "月龄":'';
        var day = parseInt(days%30) > 0 ? parseInt(days%30) + "天":'';
        return monthAge + day
    };
    //按钮的状态：
    var isChecked = function(scoreObj){
        for(var item in scoreObj){
            if(!$.isEmptyObject(scoreObj[item])){
                if($("#"+item).parent('div').attr("isEnding") == "end"){
                    $("#"+item).parent('div').addClass("done");
                }else if($("#"+item).parent('div').attr("isEnding") == "going"){
                    $("#"+item).parent('div').addClass("transition");
                }
            }
        }
    };
    /*
    * 渲染问卷：
    * */
    event.quesInit = function(data,quesType,diff,startId,scoreObj,start,end){
        var _this = this;
        var stage = _this.stageArr(data,diff,quesType,startId);
        var stageName = stage.stage,defaultId = stage.defaultId;
        var initData = _this.stageShowLength(stage.stageArr,quesType,defaultId);
        $ui.stageTabInit({"id":"#stage-tabs","data": initData});
        var ques = data[quesType][stageName];
        for(var i = 0 ;i<ques.questions.length;i++){
            ques.questions[i].type = quesType;
            ques.questions[i].stageName = stageName;
        }
        $ui.bsidInit({"id":"#main","data":ques.questions});

        var initId =$("div.stage.selected").attr("initId");//当前阶段下的开始id
        var endId =$("div.stage.selected").attr("endId");//当前阶段下的结束id
        var length =$("div.stage.selected").attr("length");//tab列表的长度；
        var groupIds = _this.groupIds(data,quesType);//获取每个年龄段题目id的数组；
        _this.countScore(data,scoreObj,initId,endId,length,groupIds);
        _this.stageTabArr(data,scoreObj);
        _this.stageTab(data,scoreObj);
    };
    /*
    * 阶段
    * */
    event.stageArr = function(data,diff,quesType,startId){
        var _this = this;
        var stageArr = [],stageId = 1,stage,defaultId,initId,status;
        for(var item in data[quesType]){
            var defaultFlag = "";
            if(!defaultFlag){
                if(!startId){
                    var days = _this.totalDays(data[quesType][item].range);
                    if( days.days0.toFixed(0) <= diff*1 && days.days1.toFixed(0) >= diff*1 ){
                        defaultFlag = true;
                    }
                }else{
                    if(startId == stageId){
                        defaultFlag = true;
                    }
                }
            }
            if(defaultFlag){
                stage = item;
                defaultId = stageId;
            }
            var lens = data[quesType][item].questions.length;
            stageArr.push({
                "stage":item,
                "range":data[quesType][item].range,
                "id":stageId,
                "defaultFlag":defaultFlag,
                "quesType":quesType,
                "initId":data[quesType][item].questions[0].id,
                "endId":data[quesType][item].questions[lens-1].id,
                "status":data[quesType][item].status
            });
            stageId++;
        }
        var length = stageArr.length;
        for(var i = 0;i<stageArr.length;i++){
            stageArr[i].length = length;
        }
        if(!defaultId){
            if(diff*1 < 16){var pos = 0;}else{pos = length-1}
            defaultId = stageArr[pos].id;
            stage = stageArr[pos].stage;
            stageArr[pos].defaultFlag = true;
        }
        return {
            "stageArr":stageArr, //stageTab数组
            "stage":stage,  //选中的stageTab的阶段名
            "defaultId":defaultId//默认选中的stageTab的id
        };
    };
    /*
    * 获取分测试中某个年龄段的题目ID数组
    * */
    event.groupIds = function(data,quesType){
        var groupIds = {};
        for(var item in data[quesType]){
            var questions = data[quesType][item].questions;
            var arr  = [];
            for(var i = 0;i< questions.length ;i++){
                arr.push(questions[i].id);
            }
            groupIds[item] = arr;
        }
        return groupIds;
    };
    event.groupIdsLength = function(groupIds){
        var length = 0;
        for(var item in groupIds){
            length+= groupIds[item].length*1;
        }
        return length;
    }
    /*
    * stageTab展示长度：
    * */
    event.stageShowLength = function(data,quesType,defaultId){
        var lens = data.length;defaultId = defaultId*1;
        var length = Math.ceil(lens/5);
        for(var i=0;i<data.length;i++){
          if(defaultId < 5){
              if(data[i].id <= 5){
                  data[i].showFlag = true;
              }else{
                  data[i].showFlag = false;
              }
          }else if((length-1)*5 < defaultId && defaultId <= length*5){
              if(data[i].id > lens-5 ){
                  data[i].showFlag = true;
              }else{
                  data[i].showFlag = false;
              }
          }else{
              if(data[i].id >= defaultId && data[i].id <= defaultId*1 + 4 ){
                  data[i].showFlag = true;
              }else{
                  data[i].showFlag = false;
              }
          }
        }
        var count = Math.floor(defaultId/5);
        return {
          "prev":count,
          "next":count+1,
          "length":length,
          "data":data,
          "quesType":quesType
        };
    };
    /*
    * xx月xx天   转为  总天数
    * */
    event.totalDays = function(stageStr){
        var first = stageStr.substring(0,stageStr.indexOf("~"));
        var last = stageStr.substring(stageStr.indexOf("~")+1);
        return {
            "days0":days(first),
            "days1":days(last)
        };
    };
    var days = function(str){
        var days;
        if(str.indexOf("月") == "-1"){
            days = str.substring(0,str.indexOf("天"))*1;
        }else{
            days = str.substring(0,str.indexOf("月"))*30.4 + str.substring(str.indexOf("月")+1,str.indexOf("天"))*1;
        }
        return days;
    };
    /*
     * 计算分数：
     * */
    event.countScore = function(data,scoreObj,initId,endId,length,groupIds){
        var _this = this;
        _this.scoreChecked(data,scoreObj,initId,endId,length,groupIds);
        //允许修改最后一个：
        $("#main").off("click",'div[class*="item-mask"]');
        $("#main").on("click",'div[class*="item-mask"]',function(){
                if($("#testSelect>div.selected").attr("isEnding")!="end"){
                var maskId = $(this).attr("maskId");
                var lastId = $("#testSelect>div.selected").attr("lastId");
                var startId = $("#testSelect>div.selected").attr("startId");
                var quesType = $("#testSelect>div.selected").attr("quesType");
                var series = $("#testSelect>div.selected").removeAttr("seriesstage");
                if(lastId*1 == maskId*1){
                    var stage = $(this).attr("stage");
                    delete scoreObj[quesType][lastId];
                    var questions = data[quesType][stage].questions;
                    delEva(questions, lastId);
                    $(this).parents("div.item").removeClass('ans bg-0').find("div.item-mask").removeClass("score-0").addClass("hide");
                    if(startId  && startId*1+2 == lastId*1){
                        delAll1(data,quesType,startId,scoreObj);
                        $("#node").find(".initialNode>div").eq(1).html("未检测到");
                        $("#testSelect>div.selected").removeAttr("start startId");
                    }
                }else{
                    $bb.toastShow("当前不可以修改",1500);
                }
            }
        })
    };
    /*
    * 行为评估点击事件
    * */
    event.behaviorFn = function(data,quesType,scoreObj){
        $("#main").off("click","table tbody tr.yes td>div[behavior]");
        $("#main").on("click","table tbody tr.yes td>div[behavior]",function(){
            if($(this).parent("td").attr("end") != 'end'){
                var history = $("#backTo").attr("history");
                history = history ? JSON.parse(history):[];
                var behaviorNow = $(this).attr("behavior"),beId = $(this).attr("beId");
                $(this).html('<i class="fa fa-check-circle" aria-hidden="true"></i>').siblings().addClass("bg-grey");
                history.push(behaviorNow);
                $("#backTo").attr("history",JSON.stringify(history));
                //判断本行是否隐藏：
                var typeB = behaviorNow.substring(0,1);
                var index = $(this).index();
                for(var  i = 0;i<data[quesType].questions.length;i++){
                    if(data[quesType].questions[i].id*1 == beId*1){
                        data[quesType].questions[i][typeB] = index+1;
                    }
                }
                if(!scoreObj[quesType][beId]){
                    scoreObj[quesType][beId] = {};
                }
                scoreObj[quesType][beId][typeB] = index+1;
                var type = typeB =="a" ? "b":"a";
                for(var i = 0 ;i<history.length;i++){
                    if(history[i].indexOf(type+"."+beId)>=0){
                        $(this).parents("tr").css("display","none");
                        break;
                    }
                }
                data[quesType].history = JSON.stringify(history);
                $(this).parent("td").attr("end","end");
            }
        });
        $("#main").off("click","#backTo");
        $("#main").on("click","#backTo",function(){
            var history = $(this).attr("history");
            history = history ? JSON.parse(history):[];
            if(history.length == 0){
                $bb.toastShow("当前问卷还没有开始做，无法返回上一步",1500);
            }else{
                var last = history[history.length-1];
                var type = last.substring(0,1),beId = last.substring(2,last.indexOf("-"));
                $('div[behavior="'+last+'"]').parent("td").removeAttr("end");
                $('div[behavior="'+last+'"]').parents("tr").removeAttr("style");
                $('div[behavior="'+last+'"]').html('<i class="fa fa-circle-thin" aria-hidden="true"></i>').siblings().removeClass("bg-grey");
                history.pop();
                for(var  i = 0;i<data[quesType].questions.length;i++){
                    if(data[quesType].questions[i].id*1 == beId*1){
                        delete data[quesType].questions[i][type];
                    }
                }
                delete scoreObj[quesType][beId][type];
                $(this).attr("history",JSON.stringify(history));
                data[quesType].history = JSON.stringify(history);
            }
        });
    };

    /*
     * 分数选择
     * */
    event.scoreChecked = function(data,scoreObj,initId,endId,length,groupIds){
        var _this = this;
        $("#main").off("click","div[score]");
        $("#main").on("click","div[score]",function(){
            if(!$(this).parents("div.item").hasClass('bg-0')){
                if($("#testSelect>div.selected").attr("isEnding")!="end"){
                    var quesId = $(this).parent("div.item-scores").attr("id");
                    var score = $(this).attr("score");
                    var quesType = $(this).attr("quesType");
                    var stage = $(this).attr("stage");
                    $('.stages>div[stage="'+stage+'"]').attr('isEnding',"going");
                    $("#"+quesType).parent("div").attr("isEnding","going");
                    data[quesType][stage].status = 1;//status 1:过渡，2，当前，3，完成；
                    $("#stage-tabs").find('div[stage="'+stage+'"]').addClass("transition").removeClass("done");
                    var questions = data[quesType][stage].questions;
                    var start = $("#"+quesType).parent("div").attr("start");
                    var end = $("#"+quesType).parent("div").attr("end");
                    var isEnding = $("#"+quesType).parent("div").attr("isEnding");
                    var startFlag = start ? true:false;
                    var endFlag = end ? true:false;
                    var seriesStage =  $("#testSelect>div.selected").attr("seriesStage");
                    var idArr = [];
                    for(var item in scoreObj[quesType]){idArr.push(item);}
                    var minId1 = Math.min.apply(null,idArr);
                    $("#testSelect>div.selected").attr("lastId",quesId);
                     var gLength = _this.groupIdsLength(groupIds,quesType);
                    var thisdom = this;
                    if(seriesStage){
                        var seriesBefore =JSON.parse($("#testSelect>div.selected").attr("seriesStage"));
                        scoreObj[quesType][quesId] = score;
                        addClassFn(score,thisdom,questions,quesId);
                        var beforeIsEnd = isStageEnd(groupIds,scoreObj,quesType,seriesBefore[0]);
                        if(isStageEnd(groupIds,scoreObj,quesType,stage)){
                            data[quesType][stage].status = 3;
                            $("#stage-tabs").find('div[stage="'+stage+'"]').addClass("done").removeClass("transition");
                        }
                        if(score == 0){//返回之前的阶段
                            delBg0(data,quesType);
                            $("#testSelect>div.selected").removeAttr("seriesStage");
                            //判断之前的阶段是否完成
                            if(!beforeIsEnd){
                                $('.stages>div[stage="'+seriesBefore[0]+'"]').click();
                            }else{
                                initId0 = getInit0(scoreObj,quesType);
                                if(!startFlag){
                                    startFalse(data,scoreObj,quesType,'',minId1);
                                }else{
                                    startTrue(data,scoreObj,quesType,minId1*1);
                                }
                            }
                        }
                        if(score == 1){
                            if(!startFlag){
                                var nowFlag3 = startFlagFn(minId1,scoreObj,quesType);//最小题号的第一个，第二个，第三个 都为1，找到起始节点；
                                if(nowFlag3){
                                    startFlag = true;
                                    var startStage = startStageFn(data,quesType,minId1);
                                    scoreObj["start"][quesType] = startStage;
                                    scoreObj["startId"][quesType] = minId1;
                                    $("#"+quesType).parent("div").attr({"start":startStage,"startId":minId1});
                                    $bb.toastShow("找到起始节点",1500);
                                    all1(data,quesType,quesId,scoreObj);
                                    $("#node").find(".initialNode>div").eq(1).html(startStage);
                                }
                            }
                            if($(this).attr("series")){
                                seriesFn(thisdom,data,quesType,scoreObj,stage);
                            }else{
                                delBg0(data,quesType);
                                $("#testSelect>div.selected").removeAttr("seriesStage");
                                if(!beforeIsEnd){
                                    $('.stages>div[stage="'+seriesBefore[0]+'"]').click();
                                }else{
                                    if(!startFlag){
                                        initId0 = getInit0(scoreObj,quesType);
                                        if(initId0){
                                            if(!startFlag){
                                                startFalse(data,scoreObj,quesType,initId0,minId1);
                                            }else{
                                                startTrue(data,scoreObj,quesType,initId0);
                                            }
                                        }else{
                                            startFalse(data,scoreObj,quesType,initId0,minId1);
                                        }
                                    }else{
                                        if(nowFlag3){
                                            startTrue(data,scoreObj,quesType,minId1);
                                        }else{
                                            var k = 0;
                                            do{
                                                k++;
                                            }while(scoreObj[quesType][minId1*1+k]*1 >= 0);
                                            var stageNext = startStageFn(data,quesType,minId1*1+k);
                                            $('.stages>div[stage="'+stageNext+'"]').click();
                                        }
                                    }
                                }
                            }
                        }

                    }else{
                        if(score == 0 && quesId <=3){
                            var tpl0 = {
                                title:"提示",
                                tips:"最低阶段无法通过，即0分",
                                btn1:"知道了,进行下一项",
                                btn0:"再测一遍"
                            };
                            var callFn01 = function(){
                                startFlag = true;
                                endFlag = true;
                                var endStage = startStageFn(data,quesType,quesId);
                                scoreObj[quesType][quesId] = score;
                                evaluate(questions,quesId,score);
                                if(isStageEnd(groupIds,scoreObj,quesType,stage)){
                                    data[quesType][stage].status = 3;
                                    $("#stage-tabs").find('div[stage="'+stage+'"]').addClass("done").removeClass("transition");
                                }
                                $("#testSelect>div.selected").attr({"startId":endStage,"end":endStage,"isEnding":"end"});
                                $("#main").off("click","div[score]");
                                $("#"+quesType).html(0);
                                var notDo = notDoFn();
                                if(notDo.length > 0){
                                    $("#testSelect").find('div.item-label[quesType="'+notDo[0]+'"]').click();
                                }else{
                                    $("#topbar").find("li").eq(0).click();//父页面按钮点击事件
                                }
                            };
                            var callFn02 = function(){
                                scoreObj[quesType] = {};
                                delEvaAll(data[quesType]);
                                $("#testSelect").find('div.item-label.selected').click();
                            };
                            _this.dialog(tpl0,callFn01,callFn02);
                        }else{
                            if(isEnding != "end"){
                                var isStart,initId0;
                                if(!startFlag){
                                    if(initId != quesId && !(scoreObj[quesType][initId]*1 >= 0)){
                                        $bb.toastShow("起始节点未找到，请按顺序做题",1500);
                                    }else if(initId != quesId){
                                        if(quesId == initId*1 + 1){
                                            addClassFn(score,thisdom,questions,quesId);
                                            scoreObj[quesType][quesId] = score;
                                            if(score == 1 && $(this).attr("series")){seriesFn(thisdom,data,quesType,scoreObj,stage);}
                                        }else if(quesId == initId*1 + 2  && scoreObj[quesType][initId*1+1]*1 == 1){
                                            addClassFn(score,thisdom,questions,quesId);
                                            scoreObj[quesType][quesId] = score;
                                            if(score == 1 && $(this).attr("series")){seriesFn(thisdom,data,quesType,scoreObj,stage);}
                                        }else{
                                            if(!scoreObj[quesType][initId*1+2]*1){
                                                $bb.toastShow("起始节点未找到，请按顺序做题",1500);
                                            }else{
                                                addClassFn(score,thisdom,questions,quesId);
                                                scoreObj[quesType][quesId] = score;
                                                if(score == 1 && $(this).attr("series")){seriesFn(thisdom,data,quesType,scoreObj,stage);}
                                            }
                                        }
                                    }else if(initId == quesId){
                                        addClassFn(score,thisdom,questions,quesId);
                                        scoreObj[quesType][quesId] = score;
                                        if(score == 1 && $(this).attr("series")){seriesFn(thisdom,data,quesType,scoreObj,stage);}
                                    }
                                    initId0 = getInit0(scoreObj,quesType);
                                    var startEnd = isStageEnd(groupIds,scoreObj,quesType,stage);//判断本阶段是否结束
                                    if(initId0){
                                         isStart = isStartFn(scoreObj,quesType,initId0);//判断0是否在当前阶段
                                         if(!isStart && $.inArray(initId0*1,groupIds[stage])>=0) {
                                             var k = 0;
                                             do{
                                                 k++;
                                             }while(scoreObj[quesType][initId0-k] == 1);
                                             var ofStage = startStageFn (data,quesType,initId0-k);
                                             $('.stages>div[stage="' + ofStage + '"]').click();
                                         }else{
                                             jumpFn(startEnd,data,quesType,endId*1+1);
                                         }
                                    }else{
                                        jumpFn(startEnd,data,quesType,endId*1+1);
                                    }
                                    if(isStageEnd(groupIds,scoreObj,quesType,stage)){
                                        data[quesType][stage].status = 3;
                                        $("#stage-tabs").find('div[stage="'+stage+'"]').addClass("done").removeClass("transition");
                                    }
                                    var nowFlag3 = startFlagFn(minId1,scoreObj,quesType);//最小题号的第一个，第二个，第三个 都为1，找到起始节点；
                                    if(nowFlag3){
                                        startFlag = true;
                                        var startStage = startStageFn(data,quesType,minId1);
                                        scoreObj["start"][quesType] = startStage;
                                        scoreObj["startId"][quesType] = minId1;
                                        $("#"+quesType).parent("div").attr({"start":startStage,"startId":minId1});
                                        $bb.toastShow("找到起始节点",1500);
                                        all1(data,quesType,quesId,scoreObj);
                                        $("#node").find(".initialNode>div").eq(1).html(startStage);
                                    }
                                };
                                if(startFlag){
                                    var thisdom = this;
                                    addClassFn(score,thisdom,questions,quesId);
                                    scoreObj[quesType][quesId] = score;
                                    if(isStageEnd(groupIds,scoreObj,quesType,stage)){
                                        data[quesType][stage].status = 3;
                                        $("#stage-tabs").find('div[stage="'+stage+'"]').addClass("done").removeClass("transition");
                                    }
                                    var isEnd;
                                    var startId = $("#"+quesType).parent("div").attr("startId");
                                    for(var item in scoreObj[quesType]) {
                                        if (item * 1 >= startId*1) {
                                            var empty = isEmpty(startId,data,scoreObj,quesType,item*1);
                                            if(empty){
                                                if (scoreObj[quesType][item] >= 0) {
                                                    if (scoreObj[quesType][item] == 1) {
                                                        isEnd = getEnd0(scoreObj, quesType, item*1);
                                                        if(isEnd.end){break;}
                                                    }
                                                } else {
                                                    break;
                                                }
                                            }else{
                                                break;
                                            }
                                        }
                                    }
                                    if(score == 1){
                                        var that = this;
                                        seriesFn(that,data,quesType,scoreObj,stage);
                                    }
                                     if(isEnd && isEnd.end){
                                        $("#testSelect>div.selected").attr("isEnding","end");
                                        var notDo = notDoFn();
                                        if(notDo.length >0){var tip = "保存并开始下一项";}else{tip = "去提交";}
                                        var tpl = {
                                            title:"停测",
                                            tips:"监测到连续5题0分，可以停测",
                                            btn1:tip,
                                            btn0:"返回修改"
                                        };
                                        var callFn1 = function(){
                                            endFlag = true;
                                            var endStage = startStageFn(data,quesType,isEnd.startId);
                                            $("#testSelect>div.selected").attr({"end":endStage,"isEnding":"end","endId":isEnd.startId});
                                            $("#main").off("click","div[score]");
                                            if(isStageEnd(groupIds,scoreObj,quesType,stage)){
                                                data[quesType][stage].status = 3;
                                                $("#stage-tabs").find('div[stage="'+stage+'"]').addClass("done").removeClass("transition");
                                            }
                                            scoreObj["end"][quesType] = endStage;
                                            scoreObj["endId"][quesType] = isEnd.startId;
                                           _this.scoreCount(scoreObj,quesType);
                                            $("#node").find(".endNode>div").eq(1).html(endStage);
                                            var notDo = notDoFn();
                                            if(notDo.length >0){
                                                $("#testSelect").find('div.item-label[quesType="'+notDo[0]+'"]').click();
                                            }else{
                                                $("#topbar").find("li").eq(0).click();//父页面按钮点击事件
                                            }
                                        };
                                        var that = this;
                                        var callFn2 = function(){
                                            delete scoreObj[quesType][quesId];
                                            delEva(questions, quesId);
                                            $("#testSelect>div.selected").removeAttr("isEnding");
                                            $(that).parents("div.item").removeClass('ans').find("div.item-mask").removeClass("score-0").addClass("hide");
                                        }
                                        _this.dialog(tpl,callFn1,callFn2);
                                    }else{
                                        var nowIsEnd = isStageEnd(groupIds,scoreObj,quesType,stage);
                                        var startId = $("#"+quesType).parent("div").attr("startId");
                                        if(nowIsEnd){
                                            var k = 0;
                                            do{
                                                k++;
                                            }while(scoreObj[quesType][startId*1+k]*1 >= 0);
                                            var stageNext = startStageFn(data,quesType,startId*1+k);
                                            if(!$(this).attr("series")){
                                                $('.stages>div[stage="'+stageNext+'"]').click();
                                            }
                                            if($(this).attr("series") && score == 0){
                                                $('.stages>div[stage="'+stageNext+'"]').click();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if(idArr.length+1 == gLength && startFlag && !endFlag){
                        $bb.toastShow("题目已经全部做完，停止检测");
                        endFlag = true;
                        var endStage = startStageFn(data,quesType,gLength*1);
                        $("#testSelect>div.selected").attr({"end":endStage,"isEnding":"end","endId":gLength*1});
                        $("#main").off("click","div[score]");
                        scoreObj["end"][quesType] = endStage;
                        scoreObj["endId"][quesType] = gLength*1;
                        _this.scoreCount(scoreObj,quesType);
                        $("#node").find(".endNode>div").eq(1).html(endStage);
                    }
                }
            }
        });
    };
    var jumpFn = function(startEnd,data,quesType,nextId){
        if(startEnd){
            var nextStage = startStageFn (data,quesType,nextId);
            $('.stages>div[stage="'+nextStage+'"]').click();
        }
    }
    var evaluate = function(quesArr,nowId,score){
        for(var i = 0;i<quesArr.length;i++){
            if(quesArr[i].id == nowId){
                quesArr[i].score = score;
            }
        }
    }
    var delEva = function(quesArr,nowId){
        for(var i = 0;i<quesArr.length;i++){
            if(quesArr[i].id == nowId){
                delete quesArr[i].score;
            }
        }
    }
    var delEvaAll = function(questions){
        for(var stage in questions){
            for(var i = 0;i<questions[stage].questions.length;i++){
                if(questions[stage].questions[i].score >= 0){
                    delete questions[stage].questions[i].score;
                }
            }
            delete questions[stage].status;
        }
    };
    var notDoFn = function(){
        var quesArr = ["cognition","accept","expression","fineaction","bigaction"];
        var notDo = [];
        for(var i=0;i<quesArr.length;i++){
            if($('#testSelect>div[quesType="'+quesArr[i]+'"]').attr('isEnding') != "end"){
                notDo.push(quesArr[i]);
            }
        }
        return notDo;
    };
    //添加样式：
    var addClassFn = function(score,dom,questions,quesId){
        if(score == 0 ){
            $(dom).parents("div.item").addClass('ans').find("div.item-mask").removeClass("hide score-1").addClass("score-0").find("div.item-status").html('<i class="fa fa-minus-circle" aria-hidden="true"></i>');
            evaluate(questions,quesId,score);
        }else {
            $(dom).parents("div.item").addClass('ans').find("div.item-mask").removeClass("hide score-0").addClass("score-1").find("div.item-status").html('<i class="fa fa-check-circle" aria-hidden="true"></i>');
            evaluate(questions, quesId, score);
        }
    }
     //遍历scoreObj:获取初始值为0的id
    var getInit0 = function(scoreObj,type){
        for(var item in scoreObj[type]){
            if(scoreObj[type][item] == 0){
                return item;
            }
        }
    };
    var isStartFn = function(scoreObj,quesType,initId0){
        var isStart =true;
        for(var i = initId0-3;i< initId0;i++ ){
            if(scoreObj[quesType][i] !=1 ){
                isStart = false;
            }
        }
        return isStart;
    };
    var startStageFn = function(data,quesType,initId0){
        for(var item in data[quesType]){
            for(var i = 0;i<data[quesType][item].questions.length;i++){
                if(initId0 == data[quesType][item].questions[i].id){
                    return item;
                }
            }
        }
    };
    var isStageEnd = function(groupIds,scoreObj,quesType,stage){
        var nowEnd = true;
        for(var i = 0;i<groupIds[stage].length;i++){
            if(!(scoreObj[quesType][groupIds[stage][i]]*1 >= 0)){
                nowEnd = false;
            }
        }
        return nowEnd
    };
    //如果找到起始点，则之前的全部为1：
    var all1 = function(data,quesType,startId,scoreObj){
        for(var item in data[quesType]){
            for (var i = 0; i < data[quesType][item].questions.length; i++) {
                if (data[quesType][item].questions[i].id*1 < startId) {
                    if(!data[quesType][item].questions[i].score){
                        data[quesType][item].questions[i].score = 1;
                        data[quesType][item].questions[i].scoreType = 1;
                        evaluate(data[quesType][item].questions,data[quesType][item].questions[i].id*1,1);
                        data[quesType][item].status = 3;
                        scoreObj[quesType][data[quesType][item].questions[i].id] = 1;
                        $("#stage-tabs").find('div[stage="'+item+'"]').addClass("done");
                    }
                }
            }
        }
    };
    var delAll1 = function(data,quesType,startId,scoreObj){
        for(var item in data[quesType]){
            for (var i = 0; i < data[quesType][item].questions.length; i++) {
                if (data[quesType][item].questions[i].id*1 < startId*1) {
                     if(data[quesType][item].questions[i].scoreType == 1){
                        delete data[quesType][item].questions[i].score ;
                        delete data[quesType][item].status;
                        delete scoreObj[quesType][data[quesType][item].questions[i].id];
                        $("#stage-tabs").find('div[stage="'+item+'"]').removeClass("done");
                     }
                }
            }
        }
    };
    var delBg0 = function(data,quesType,stage){
        for(var stage in data[quesType]){
            for (var i = 0; i < data[quesType][stage].questions.length; i++) {
                if (data[quesType][stage].questions[i].bgFlag ) {
                    delete data[quesType][stage].questions[i].bgFlag
                }
            }
        }
    };
    //遍历scoreObj:startId的value值为1；
    var getEnd0 = function(scoreObj,quesType,startId){
        var end = true;
        for(var i = startId*1+1;i< startId*1+6;i++){
            if(scoreObj[quesType][i]>=0){
                if(scoreObj[quesType][i] == 1){
                    end = false;
                    break;
                }
            }else{
                end = false;
                break;
            }
        }
        return {
            "end":end,
            "startId":startId
        };
    };
    //同系列跳转：
    var seriesFn = function(dom,data,quesType,scoreObj,beforeStage){
        var series = $(dom).attr("series");
        if(series) {
            var beforeStageArr = $("#testSelect>div.selected").attr("seriesStage");
            beforeStageArr ? beforeStageArr = JSON.parse(beforeStageArr):beforeStageArr = [];
            beforeStage ? beforeStageArr.push(beforeStage):beforeStageArr;
            var index = series.indexOf(":");
            var toId = series.substring(0, index);
            var stageName = series.substring(index + 1);
            for (var i = 0; i < data[quesType][stageName].questions.length; i++) {
                if (data[quesType][stageName].questions[i].id != toId*1) {
                    data[quesType][stageName].questions[i].bgFlag = true;
                }else{
                    delete data[quesType][stageName].questions[i].bgFlag
                }
            }
            if(scoreObj[quesType][toId] >= 0){
                 delBg0(data,quesType);
                $bb.toastShow("该同系列题目已经做过",1500);
                var initId0 = getInit0(scoreObj,quesType);
                var idArr = [];
                for(var item in scoreObj[quesType]){idArr.push(item);}
                var minId1 = Math.min.apply(null,idArr);
                var startFlag = startFlagFn(minId1*1,scoreObj,quesType);
                if(startFlag){
                    var ofStage = startStageFn (data,quesType,minId1*1);
                    $("#testSelect>div.selected").attr({"startId":minId1*1,"start":ofStage});
                    scoreObj['startId'][quesType] = minId1*1;
                    scoreObj['start'][quesType] = ofStage;
                    startTrue(data,scoreObj,quesType,minId1*1);
                }else{
                   if(initId0){
                       var k = 0;
                       do{
                           k++;
                       }while(scoreObj[quesType][initId0-k] == 1);
                       var ofStage = startStageFn (data,quesType,initId0-k);
                       $("#testSelect>div.selected").removeAttr("seriesStage");
                       $('.stages>div[stage="' + ofStage + '"]').click();
                   }
                }
            }else{
                $('.stages>div[stage="' + stageName + '"]').click();
                $("#testSelect>div.selected").attr("seriesStage",JSON.stringify(beforeStageArr));
            }
        }
    };
    //找到初始点时题目的跳转：
    var startTrue = function(data,scoreObj,quesType,initId0){
        var k = 0;
        do{
            k++;
        }while(scoreObj[quesType][initId0*1+k]*1 >= 0);
        var stageNext = startStageFn(data,quesType,initId0*1+k);
        $('.stages>div[stage="'+stageNext+'"]').click();
    }
    //未找到初始点时题目的跳转：
    var startFalse = function(data,scoreObj,quesType,initId0,minId1){
         var k = 0;
        do{
            k++;
        }while(scoreObj[quesType][minId1*1 - k] >= 0);
        var ofStage = startStageFn (data,quesType,minId1*1 -  k);
        $('.stages>div[stage="'+ofStage+'"]').click();
    }

    //判断是否有空题：从起始节点到当前
    var isEmpty = function(startId,data,scoreObj,quesType,nowId0){
        var isEmpty = true;
        for(var i = startId*1 ; i< nowId0*1;i++){
            if(!(scoreObj[quesType][i] >= 0)){
                isEmpty = false;
            }
        }
        return isEmpty
    }
    /*
    * 弹窗事件：
    * tpl:渲染弹窗的字段；
    * callback1 :按钮的flag==1 的回调函数；
    * callback0 :按钮的flag==0 的回调函数；
    * params:其他参数
    * */
   event.dialog = function(tpl,callback1,callback0,params){
       $ui.dialogInit({"id":"#myModalTpl","data":tpl});
       $("#myModalTpl").off("click",".modal-footer>button");
       $("#myModalTpl").on("click",".modal-footer>button",function(){
           var flag = $(this).attr("flag");
           if(flag == "1"){
                if(callback1 && typeof callback1 == 'function'){
                    params ? callback1(params):callback1();
                }
           }else if(flag == "0"){
               if(callback0 && typeof callback0 == 'function'){
                   params ? callback0(params):callback0();
               }
           }
       });
       $('#myModal').modal({backdrop: "static",keyboard:false,show:true});//点击背景空白处不会关闭；按下键盘esc不会被关闭
    };
    /*
    * 阶段月龄的上页、下页：
    * tpl:模板渲染数据
    * callback:回调函数
    * params:传参：
    * */
   event.stageTabArr = function(data,scoreObj,startId){
      var _this = this,defaultId = 0;
      $("#stage-tabs").off("click","div[group]");
      $("#stage-tabs").on("click","div[group]",function(){
        if(!$(this).hasClass("forbidden")){
           var group = $(this).attr("group");
           var quesType = $(this).attr("quesType");
           var index = $(this).attr("index");
           if(group == "prev"){//渲染前一版
               defaultId = index*5 - 4;
           }else if(group == "next"){//渲染后一版
                defaultId = index*5 + 1;
           }
           _this.quesInit(data,quesType,'',defaultId,scoreObj);
        }
      });
   };
   event.stageTab = function(data,scoreObj){
        var _this = this;
        var number = {};
        $("#stage-tabs").off("click",".stages>div");
        $("#stage-tabs").on("click",".stages>div",number,function(e){
            if($(this).hasClass("hide")){
                var stageId = $(this).attr("stageId");
                var quesType = $(this).attr("quesType");
                var index = Math.ceil(stageId/5);
                $("#stage-tabs").find('div[group][index="'+index+'"]').click();
                _this.quesInit(data,quesType,'',stageId,scoreObj);
            }
            var stage = $(this).attr("stage");
            var quesType = $(this).attr("quesType");
            $(this).addClass('selected').siblings().removeClass("selected");
            for(var i = 0 ;i<data[quesType][stage].questions.length;i++){
                data[quesType][stage].questions[i].type = quesType;
                data[quesType][stage].questions[i].stageName = stage;
                if(data[quesType][stage].questions[i].id == e.number*1){
                    data[quesType][stage].questions[i].bgFlag = true;
                }
            }
            $ui.bsidInit({"id":"#main","data":data[quesType][stage].questions});
            var initId =$(this).attr("initId");
            var endId =$(this).attr("endId");
            var length =$(this).attr("length");
            var groupIds = _this.groupIds(data,quesType);
            _this.countScore(data,scoreObj,initId,endId,length,groupIds);
        });
    };
    /*
    * 智龄计算：
    * */
    event.intelligenceAge = function(diff,lastAge){
        var days = 0;
        if(lastAge.indexOf("月") >= 0 && lastAge.indexOf("天") >= 0){ // 1月5天
            days = lastAge.substring(0,lastAge.indexOf("月"))*30 + lastAge.substring(lastAge.indexOf("月")+1,lastAge.indexOf("天"))*1;
        }else if(lastAge.indexOf("月") >= 0){ // 3月,>3月
            if(lastAge.indexOf(">") >= 0){
                days = lastAge.substring(lastAge.indexOf(">")+1,lastAge.indexOf("月"))*30;
            }else if(lastAge.indexOf("-") >= 0){  // 28月 - 30月；
                days = lastAge.substring(0,lastAge.indexOf("月"))*30;
            }else{
                days = lastAge.substring(0,lastAge.indexOf("月"))*30;
            }
        }else if(lastAge.indexOf("天") >= 0){  //   <16天  ，16天；
            if(lastAge.indexOf("<") >= 0) {
                days = lastAge.substring(lastAge.indexOf("<") + 1, lastAge.indexOf("天")) * 1;
            }else{
                days = lastAge.substring(0,lastAge.indexOf("天"))*1;
            }
        }else{
            days = lastAge*30;
        }
        return days+diff*1;
    };
    event.scoreCount = function(scoreObj,quesType){
        var startId = scoreObj.startId[quesType];
        var endId = scoreObj.endId[quesType];
        var score = 0;
        for(var item in scoreObj[quesType]){
            if(item*1 <= endId*1 && item*1 > startId*1){
                score += scoreObj[quesType][item]*1;
            }
        }
        score += startId*1;
        $("#"+quesType).html(score);
    };
    event.getScoreClick = function(scoreObj,userId,type){
        var submissionResult = function(){
            var posId = {
                "score":{
                    "cogScore": parseFloat($("#cognition").html()) >=0 ? $("#cognition").html() : 0 , //认知原始分
                    "RCSocre": parseFloat($("#accept").html()) >=0 ? $("#accept").html() : 0 ,  //接受性交流原始分
                    "ECSocre": parseFloat($("#expression").html()) >=0 ? $("#expression").html() : 0 ,  //表达性交流原始分
                    "FMSocre": parseFloat($("#fineaction").html()) >=0 ? $("#fineaction").html() : 0 ,  //精细运动原始分
                    "GMSocre": parseFloat($("#bigaction").html()) >=0 ? $("#bigaction").html() : 0   // 大运动原始分
                },
                "careAgency":$.trim($("#careAgency").val()),
                "reason":$.trim($("#testReason").val()),
                "ques":scoreObj
            };
            var getScoreFn = function(result){
                $bb.openPage('bsidResult3',{
                    "type":type,
                    "userId":userId
                });
            };
            var scoreParams = $servers.scoreParams(type,posId,'',userId);
            var notDo = notDoFn();
            if(notDo.length > 0){
                var finalNotDo = [];
                for(var  i = 0;i<notDo.length;i++){
                    var ques = notDo[i] == "accept" ? "接受性交流" :  notDo[i] == "bigaction" ? "大动作":notDo[i] == "cognition" ? "认知":notDo[i] == "fineaction" ?"精细动作":"表达性交流";
                    finalNotDo.push(ques);
                }
                $bb.toastShow(finalNotDo.join('、')+"还没有做完，请全部做完之后再提交");
            }else{
                if($.isEmptyObject(scoreObj['behavior'])){
                    var callFn = function(){
                        $servers.getScore(scoreParams,getScoreFn);
                    };
                    $bb.toastConfirmShow(callFn,'',"行为观察目录还未做，确定提交么？");
                }else{
                    $servers.getScore(scoreParams,getScoreFn);
                }
            }
        }
        var topbars = [
            {
                "icon":"fa fa-print",
                "name":"提交结果",
                "callback":submissionResult
            }
        ];
        $bb.toolbar(topbars);
    };
    /*
    * 历史问卷渲染数据处理：
    * */
    event.historyDeal = function(data,scoreObj){
        for(var item in data){
            if(item != "behavior"){
                for(var stage in data[item]){
                    for(var i = 0;i< data[item][stage].questions.length;i++){
                        if(scoreObj[item][data[item][stage].questions[i].id]*1 >= 0){
                            data[item][stage].questions[i].score = scoreObj[item][data[item][stage].questions[i].id]*1;
                        }
                    }
                }
            }else{
                for(var  i = 0;i<data[item].questions.length;i++){
                    if(scoreObj[item][data[item].questions[i].id]){
                        data[item].questions[i].a = scoreObj[item][data[item].questions[i].id].a;
                        data[item].questions[i].b = scoreObj[item][data[item].questions[i].id].b;
                    }else{
                        data[item].questions[i].a ='4';
                        data[item].questions[i].b = '4';
                    }
                }
            }
        }
        return data;
    };
    /*
    * 历史记录tab状态处理：
    * */
    event.historyTabDeal = function(data,scoreObj){
        for(var item in data){
            if(item != "behavior"){
                for(var stage in data[item]){
                    for(var i = 0;i< data[item][stage].questions.length;i++){
                        if(scoreObj[item][data[item][stage].questions[i].id]*1 >= 0){
                            var flag = true;
                            for(var i = 0;i< data[item][stage].questions.length;i++){
                                if(!(scoreObj[item][data[item][stage].questions[i].id]*1 >= 0)){
                                    flag = false;
                                }
                            }
                            flag ? data[item][stage].status =3 :data[item][stage].status =1;
                        }
                    }
                }
            }
        }
        return data;
    };

     /*
    * 起始点：
    * */
    var startFlagFn = function(initId,scoreObj,quesType){
        var startFlag = false;
        if(scoreObj[quesType][initId]*1 && scoreObj[quesType][initId*1+1]*1 && scoreObj[quesType][initId*1+2]*1){
            startFlag = true;
        }
        return startFlag
    }
    return event;
});